/*

 */
package com.ohos.connect.devicecloud.iot.modular.device.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ohos.connect.devicecloud.app.api.ProjectDeviceApi;
import com.ohos.connect.devicecloud.common.timer.CommonTimerTaskRunner;
import com.ohos.connect.devicecloud.iot.modular.device.model.entity.Device;
import com.ohos.connect.devicecloud.iot.modular.device.service.DeviceService;
import com.ohos.connect.devicecloud.mqtt.api.MqttApi;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

/**
 * 设备状态定时任务
 *
 * @author mzq
 */
@Slf4j
@Component
public class DeviceStatusUpdateTaskRunner implements CommonTimerTaskRunner {
    @Autowired
    private DeviceService deviceService;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private ProjectDeviceApi projectDeviceApi;
    @Resource
    private MqttApi mqttApi;
    @Value("${iot.redis.prefix}")
    private String IOT_REDIS_PREFIX = "iot";

    @Override
    public void action() {
        Map<String, Map<String, String>> iotKeyValues = getIotKeyValues();
        List<Device> list = deviceService.list(new QueryWrapper<Device>().lambda().eq(Device::getStatus, "online"));
        for (Device device : list) {
            String devId = device.getId();
             Map<String, String> stringStringMap = iotKeyValues.get(IOT_REDIS_PREFIX + devId);
            if (stringStringMap != null && stringStringMap.get("state") != null) {
                device.setStatus("offline");
                deviceService.updateById(device);
            }
        }
    }

    public Map<String, Map<String,String>> getIotKeyValues() {
        Map<String, Map<String,String>> result = new HashMap<>();
        // 构建扫描选项：匹配前缀"iot*"，每次扫描100条
        ScanOptions options = ScanOptions.scanOptions()
            .match("iot*")
            .count(100)
            .build();
        try (Cursor<byte[]> cursor = redisTemplate.getConnectionFactory().getConnection().scan(options)) {
            //  遍历游标，获取键和值
            while (cursor.hasNext()) {
                // 获取键（字节数组转字符串）
                byte[] keyBytes = cursor.next();
                String key = new String(keyBytes);
                // 根据实际数据类型获取值
                String state = (String) redisTemplate.boundHashOps(key).get("state");
                Map<String, String> deviceMap = new HashMap<>();
                deviceMap.put("state", state);
                result.put(key, deviceMap);
            }
        } catch (Exception e) {
            log.error("获取键值出错: {}", e.getMessage());
        }
        return result;
    }



}
